const Koa = require("koa");
const router = require("koa-router")();
const bodyParser = require("koa-bodyparser");
const app = new Koa();


// log request URL
app.use(async (ctx, next) => {
    console.log(ctx.request);
    await next()
})

// add url-router
router.get("/hello/:name", async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>Hello, ${name || "world"}!</h1>`;
})

router.get("/", async (ctx, next) => {
    ctx.response.body = `<h1>Index</h1>
                        <form action="/signin" method="post">
                        <p>Name: <input name="name" value="koa"></p>
                        <p>Password: <input name="password" type="password"></p>
                        <p><input type="submit" value="Submit"></p>
                        </form>`;
})
router.post("/signin", async (ctx, next) => {
    var name = ctx.request.body.name || "";
    var password = ctx.request.body.password || "";
    console.log(`singin with name: ${name}, password: ${password}`);
    if (name === 'koa' && password === '123456') {
        ctx.response.body = `<h1>welcome, ${name}!</h1>`;
    } else {
        ctx.response.body = `<h1>login failed</h1>
            <p><a href="/">TRY again</a></p>`;
    }
})

/**
 * 由于middleware的顺序很重要，这个koa-bodypareser 必须在router之前注册到
 * app对象上
 */

// add router middleware

app
    .use(bodyParser())
    .use(router.routes())
    .on('error', console.error)
    .listen(3000);

console.log(`app started at 3000`)